from errors import Duplicate, Missing
from model.explorer import Explorer

from .init import IntegrityError, curs

curs.execute(
    """
    CREATE TABLE IF NOT EXISTS explorer(
        name TEXT PRIMARY KEY,
        country TEXT,
        description TEXT
    )
    """
)


def _row_to_model(row: tuple) -> Explorer:
    return Explorer(name=row[0], country=row[1], description=row[2])


def _model_to_dict(explorer: Explorer) -> dict:
    return explorer.model_dump()


def get_one(name: str) -> Explorer:
    query = "SELECT * FROM explorer WHERE name = :name"
    curs.execute(query, {"name": name})
    row = curs.fetchone()
    if row:
        return _row_to_model(row)
    raise Missing(msg=f"Explorer {name} not found")


def get_all() -> list[Explorer]:
    query = "SELECT * FROM explorer"
    curs.execute(query)
    return [_row_to_model(row) for row in curs.fetchall()]


def create(explorer: Explorer) -> Explorer:
    query = """
    INSERT INTO explorer (name, country, description)
    VALUES (:name, :country, :description)
    """
    try:
        curs.execute(query, _model_to_dict(explorer))
    except IntegrityError as ex:
        raise Duplicate(msg=f"Explorer {explorer.name} already exists") from ex
    return get_one(explorer.name)


def modify(name: str, explorer: Explorer) -> Explorer:
    query = """
    UPDATE explorer
    SET name = :name, country = :country, description = :description
    WHERE name = :name_orig
    """
    params = _model_to_dict(explorer)
    params["name_orig"] = name
    curs.execute(query, params)

    if curs.rowcount == 1:
        return get_one(explorer.name)
    raise Missing(msg=f"Explorer '{name}' not found")


def delete(name: str) -> None:
    query = "DELETE FROM explorer WHERE name = :name"
    curs.execute(query, {"name": name})
    if curs.rowcount != 1:
        raise Missing(msg=f"Explorer '{name}' not found")
    return None
